#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
//存放提取出来的关键字 以及书号索引
typedef struct word
{
    int num;
    char key[MAX][MAX];
};
typedef struct node
{
    char data[MAX];
    struct node *next;
};

typedef struct index
{
    char key[MAX];
    node *next;
};

typedef struct id_list
{
    index word[MAX];
    int num;
};
char buf[MAX];
word w;
id_list list;
void inital_list()
{
    for (int i = 0; i < MAX; i++)
    {
        list.word[i].next = NULL;
    }
    list.num = 0;
}

void extract_key()
{
    w.num = 0;
    int k = 0;
    while (1)
    {
        for (int j = 0; buf[k] != ' ' && buf[k] != '\0'; j++)
        {
            w.key[w.num][j] = buf[k++];
        }
        if (buf[k] == ' ')
        {
            w.num++;
            k++;
        }
        if (buf[k] == '\0')
            return;
    }
}
int local(int j)
{
    for (int i = 0; i < list.num; i++)
    {
        if (strcmp(w.key[j], list.word[i].key) == 0)
            return i;
    }
}
void insert()
{
    for (int j = 1; j < w.num; j++)
    {
        int n = local(j);
        if (n == list.num)
        {
            strcat(list.word[list.num++].key, w.key[j]);
        }
        node *N = (node *)malloc(sizeof(node));
        N->next = NULL;
        for (int i = 0; w.key[0][i] != '\0'; i++)
        {
            N->data[i] = w.key[0][i];
        }

        N->next = list.word[n].next;
        list.word[n].next = N;
    }
}

void put_Text(FILE *g)
{
    for (int i = 0; i < list.num; i++)
    {
        char s[4 * MAX];
        strcat(s, list.word[i].key);
        node *p = list.word[i].next;
        while (p)
        {
            strcat(s, "\t");
            strcat(s, p->data);
            strcat(s, " ");
            p = p->next;
        }
        fprintf(g, "%s\n", s);
    }
}

int main()
{
    char c;
    FILE *f, *g;
    /*******************code*******************/
    if (f = fopen("bookinformation", "r+"))
    {
        if (g = fopen("index", "w"))
        {
            inital_list();

            while ((c = getc(f)) != EOF)
            {
                int i = 0;
                while (c != '\n' && c != EOF)
                {
                    buf[i++] = c;
                    c = getc(f);
                }
                buf[i] = '\0';
                extract_key();
                insert();
            }
            put_Text(g);
        }
    }

    /******************************************/
    printf("\n\n****************************\n");
    printf("Press Enter key to continue\n");
    getchar();
    return 0;
    /******************************************/
}
